package com.linln.admin.member.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
import com.github.binarywang.wxpay.bean.result.WxPayRefundResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.linln.common.constant.NoticeTypeConst;
import com.linln.common.constant.UrlConst;
import com.linln.common.enums.StatusEnum;
import com.linln.common.utils.EntityBeanUtil;
import com.linln.common.utils.MD5;
import com.linln.common.utils.ResultVoUtil;
import com.linln.common.utils.StatusUtil;
import com.linln.common.utils.ToolUtil;
import com.linln.common.vo.ResultVo;
import com.linln.modules.member.domain.MemberAgent;
import com.linln.modules.member.domain.MemberInfo;
import com.linln.modules.member.domain.MemberRefund;
import com.linln.modules.member.service.MemberAgentService;
import com.linln.modules.member.service.MemberInfoService;
import com.linln.modules.member.service.MemberRefundService;
import com.linln.modules.system.domain.Area;
import com.linln.modules.system.service.AreaService;

/**
 * @author hct
 * @date 2019/09/12
 */
@Controller
@RequestMapping("/member/agent")
public class MemberAgentController {

    @Autowired
    private MemberAgentService memberAgentService;
    @Autowired
    private AreaService areaService;
    
    @Autowired
    private MemberInfoService memberService;
    @Autowired
    private WxPayService wxPayService;
    private static final String REFUND_SUCCESS = "SUCCESS";
    @Autowired
    private MemberRefundService refundService;
    
    /**
     * 列表页面
     */
    @GetMapping("/indexold")
    @RequiresPermissions("member:agent:index")
    public String indexold(Model model, MemberAgent memberagent) {

        // 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching();
        memberagent.setStatus(StatusEnum.OK.getCode());
        // 创建匹配器，进行动态查询匹配
        

        // 获取数据列表
        Example<MemberAgent> example = Example.of(memberagent, matcher);
        Page<MemberAgent> list = memberAgentService.getPageList(example);
        List<MemberAgent> content = list.getContent();
        for (MemberAgent memberAgent :content
        ) {
            if(memberAgent==null) continue;
            Area area = areaService.findByCode(memberAgent.getArea());
            if(area != null){
                Area parea = areaService.getById(area.getPid());
                memberAgent.setAreaname(area.getName());
                if(parea != null){
                 memberAgent.setAreaname(parea.getName()+area.getName());
                }
            }
        }
        // 封装数据
        model.addAttribute("list", content);
        model.addAttribute("page", list);
        return "/member/agent/index";
    }
    /**
     * 列表页面
     */
    @GetMapping("/index")
    @RequiresPermissions("member:agent:index")
    public String index(Model model, MemberAgent memberagent,String nickname,String mobile) {

        // 创建匹配器，进行动态查询匹配
        memberagent.setStatus(StatusEnum.OK.getCode());
        MemberInfo member=new MemberInfo();
        member.setNickname(nickname);
        member.setMobile(mobile); 
        memberagent.setMember(member);
        // 创建匹配器，进行动态查询匹配
        Page<MemberAgent> list = memberAgentService.getPageList(memberagent);
        List<MemberAgent> content = list.getContent();
        List<String> areaList=new ArrayList<String>();
        for (MemberAgent memberAgent :content
        ) {
            if(memberAgent==null) continue;
            areaList.add(memberAgent.getArea());
           
        }
        List<Area> alist=areaService.findByCodeIn(areaList);
        
        for (MemberAgent memberAgent :content
                ) {
                    if(memberAgent==null || memberAgent.getArea()==null) continue;
                    for(int j=0;j<alist.size();j++) {
                    	Area area=alist.get(j);
                    	if(memberAgent.getArea().equals(area.getCode())) {
                    		Area parea = areaService.getById(area.getPid());
                            memberAgent.setAreaname(area.getName());
                            if(parea != null){
                             memberAgent.setAreaname(parea.getName()+area.getName());
                            }
                    	}
                    }
                    
                }
        // 封装数据
        model.addAttribute("list", content);
        model.addAttribute("page", list);
        return "/member/agent/index";
    }


   
    /**
     * 保存添加/修改的数据
     * @param valid 验证对象
     */
    @PostMapping("/save")
    @RequiresPermissions({"member:agent:add", "member:memberInfo:edit"})
    @ResponseBody
    public ResultVo save( MemberAgent memberInfo,Long memberId,String county,HttpServletRequest request) {
        if(memberId == null){
            return ResultVoUtil.error("用户不存在，请选择存在用户。");
        }
        if(county == null){
            return ResultVoUtil.error("请选择代理区域。");
        }
 
   	    MemberAgent memberInfonew=new MemberAgent();
   	// 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching();
        memberInfonew.setArea(county);
        memberInfonew.setStatus(null);
         // 获取数据列表
        Example<MemberAgent> example = Example.of(memberInfonew, matcher);
     	List<MemberAgent> list= memberAgentService.getList(example);
    	if(list!=null&& list.size()>0) {
    	   MemberAgent a=list.get(0);
    	    byte bsta=0;
    	   if(a.getStatus().equals(StatusEnum.OK.getCode()) || (a.getStatus().byteValue()==bsta && a.getPayStatus()==1)) {
               return ResultVoUtil.error("区域已被申请");
    	   }else {
    		    a.setStatus(StatusEnum.OK.getCode());
    		    a.setCurmoney(0d);
    	    	a.setAllmoney(0d);
    	    	MemberInfo member=new MemberInfo();
    	    	 member.setId(memberId);
    	    	a.setMember(member);
    	    	a.setCreateDate(new Date());
    	    	a.setUpdateDate(new Date());
    	    	Area area=areaService.findByCode(county);
     	    	a.setAreaname(county);
    	    	if(area!=null) {
         	    	a.setAreaname(area.getName());
    	    	}
    	    	a.setArea(county);
    	    	a.setPayStatus(1);
    	    	a.setAgentMoney(0d);
    	        memberAgentService.save(a);
    	        MemberInfo memberNew=memberService.getById(memberId);
                String md5password=MD5.getMD5String("123456");
                memberNew.setPassword(md5password);
    	    	memberNew.setIsagent(1);
                memberService.save(memberNew);
    	        return ResultVoUtil.SAVE_SUCCESS;
    	   }

    	}

    	memberInfo.setCurmoney(0d);
    	memberInfo.setAllmoney(0d);
    	MemberInfo member=new MemberInfo();
    	String md5password=MD5.getMD5String("123456");
        member.setId(memberId);
    	MemberInfo memberNew=memberService.getById(memberId);
    	memberNew.setPassword(md5password);
    	memberNew.setIsagent(1);
    	memberService.save(memberNew);
    	memberInfo.setMember(member);
    	memberInfo.setCreateDate(new Date());
    	memberInfo.setUpdateDate(new Date());
    	memberInfo.setPayStatus(1);
    	memberInfo.setAgentMoney(0d);
    	//Area area=areaService.findByName(county);
    	memberInfo.setArea(county);
    	memberInfo.setAreaname(county);
        
        // 复制保留无需修改的数据
        if (memberInfo.getId() != null) {
            MemberAgent beMemberInfo = memberAgentService.getById(memberInfo.getId());
            EntityBeanUtil.copyProperties(beMemberInfo, memberInfo);
        }

        // 保存数据
        memberAgentService.save(memberInfo);
        return ResultVoUtil.SAVE_SUCCESS;
    }

    /**
     * 跳转到详细页面
     */
    @GetMapping("/detail/{id}")
    @RequiresPermissions("member:agent:detail")
    public String toDetail(@PathVariable("id") MemberAgent memberAgent, Model model) {
        model.addAttribute("memberAgent",memberAgent);
        return "/member/agent/detail";
    }

    /**
     * 设置一条或者多条数据的状态
     */
    @RequestMapping("/status/{param}")
    @RequiresPermissions("member:agent:status")
    @ResponseBody
    public ResultVo status(
            @PathVariable("param") String param,
            @RequestParam(value = "ids", required = false) List<Long> ids) {
        // 更新状态
    	
        StatusEnum statusEnum = StatusUtil.getStatusEnum(param);
        if (memberAgentService.updateStatus(statusEnum, ids)) {
            return ResultVoUtil.success(statusEnum.getMessage() + "成功");
        } else {
            return ResultVoUtil.error(statusEnum.getMessage() + "失败，请重新操作");
        }
    }
    
    /**
     * 设置一条或者多条数据的状态
     */
    @RequestMapping("/update/{param}")
    @ResponseBody
    public ResultVo update(
            @PathVariable("param") String param,
            @RequestParam(value = "memberId", required = false) Long memberId) {
        // 更新状态
    	 MemberInfo info=memberService.getById(memberId);
			String md5password=MD5.getMD5String("123456");

    	 info.setPassword(md5password);
        if (memberService.save(info).getId()>0) {
            return ResultVoUtil.success("重置成功");
        } else {
            return ResultVoUtil.error( "重置失败，请重新操作");
        }
    }
    
    
    /**
     * 审核
     * @param model
     * @param id
     * @param storestatus  0待审核 1同意 2拒绝
     * @param request
     * @return
     */
    @GetMapping("/toshenhe/{id}")
     public String toshenhe(Model model, @PathVariable Long id,HttpServletRequest request) {
    	 model.addAttribute("id", id);
    	 return "/member/agent/toshenhe";
    }
    
    
    /**
     * 待审核列表页面
     */
    @GetMapping("/shenheindex")
    public String shenheindex(Model model, MemberAgent memberagent,HttpServletRequest request) {

        // 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching();
        Byte b=0;
        memberagent.setStatus(b);
        memberagent.setPayStatus(1);
        // 获取数据列表
        Example<MemberAgent> example = Example.of(memberagent, matcher);
        Page<MemberAgent> list = memberAgentService.getPageList(example);
        List<MemberAgent> content = list.getContent();
        for (MemberAgent memberAgent :content
        ) {
            if(memberAgent==null) continue;
            Area area = areaService.findByCode(memberAgent.getArea());
            if(area != null){
                Area parea = areaService.getById(area.getPid());
                memberAgent.setAreaname(area.getName());
                if(parea != null){
                 memberAgent.setAreaname(parea.getName()+area.getName());
                }
            }
        }
        // 封装数据
        model.addAttribute("list", list.getContent());
        model.addAttribute("page", list);
        return "/member/agent/shenheindex";
    }
    
    /**
     * 审核
     * @param model
     * @param id
     * @param storestatus  0待审核 1同意 2拒绝
     * @param request
     * @return
     */
    @PostMapping("/shenheAgent")
    @ResponseBody
    public ResultVo shenheMessage(Model model, Long id ,Integer agentStatus,HttpServletRequest request) {
    	MemberAgent agent=memberAgentService.getById(id);
    	if(memberAgentService.updateAgentStatus(agentStatus,id)) {
    	 if(agentStatus.intValue()==2) {
            	
            		//拒绝的时候将费用退回给客户 申请退款
                   WxPayRefundRequest refundInfo = WxPayRefundRequest.newBuilder()
                           //订单号
                           .outTradeNo(agent.getOrderId())
                           //退款订单号
                           .outRefundNo(ToolUtil.getRandomString(16)) 
                           //金额
                           .totalFee(yuanToFee(new BigDecimal(agent.getAgentMoney())))
                           //退款金额
                           .refundFee(yuanToFee(new BigDecimal(agent.getAgentMoney())))
                           //todo 回调地址
                           .notifyUrl(UrlConst.REFUNDNOTICEURL)
                           .build();
                   WxPayRefundResult wxPayRefundResult;
                   try {
                       wxPayRefundResult = wxPayService.refund(refundInfo);
                       //判断退款信息是否正确
                       if (REFUND_SUCCESS.equals(wxPayRefundResult.getReturnCode())
                               && REFUND_SUCCESS.equals(wxPayRefundResult.getResultCode())) {
                   		     saveRefund( agent,agent.getId());

                        }
                   } catch (WxPayException e) {
                   	return ResultVoUtil.error("异常");
                   }
            	}else if(agentStatus.intValue()==1){
            		//开放账号
            	//	saveRefund( agent,agent.getId());
            		MemberInfo member=agent.getMember();
            		if(member.getIsagent()==null || member.getIsagent().intValue()!=1) {
            			String md5password=MD5.getMD5String("123456");
            		    member.setPassword(md5password);
            		    member.setIsagent(1);
            	     	memberService.save(member);
            		}
            		
            	     
            	}
            	
            }	
    		
         return ResultVoUtil.success("审核成功");

    
    }
  
    public void saveRefund(MemberAgent agent,Long agentId) {
    	MemberRefund refund=new MemberRefund();
       	refund.setAgentId(agentId);
       	refund.setArea(agent.getArea());
       	refund.setContent("拒绝代理信息");
       	refund.setMoney(agent.getAgentMoney());
       	refund.setOrderCode(agent.getOrderId());
       	refund.setRefundmoney(agent.getAgentMoney());
       	refund.setRefundStatus(0);
       	refund.setType(NoticeTypeConst.AGENT);
       	refund.setTypeId(agent.getId());
       	refundService.save(refund);
    }
    /**
     * 1 块钱转为 100 分
     * 元转分
     *
     * @param bigDecimal 钱数目
     * @return 分
     */
    private int yuanToFee(BigDecimal bigDecimal) {
        return bigDecimal.multiply(new BigDecimal(100)).intValue();
    }

    /**
     * 时间
     *
     * @return 时间戳
     */
    private String createTimestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }
    
}